package service

import (
    "authserver/constants"
    "authserver/global"
    "authserver/model"
    "errors"
    "time"
)

// 添加音频

func AddBookAudio(audio model.BookAudio) (err error) {

    var tempAudio model.BookAudio
    if audio.BookMenuId==0{
        err = errors.New("请选择年级")
        return
    }

    if audio.LessonNum==""{
        err = errors.New("请输入章节名称")
        return
    }
    if audio.AudioUrl==""{
        err = errors.New("请输入音频地址")
        return
    }
    if audio.AudioUrl==""{
        err = errors.New("请输入封面图片")
        return
    }

    err=global.GVA_DB.Table(model.BookAudio{}.TableName()).
        Where("book_menu_id = ? and lesson_num = ?",audio.BookMenuId,audio.LessonNum).Find(&tempAudio).Error

    if tempAudio.Id!=0{
        err = errors.New("书籍已经存在")
        return
    }
    audio.Id= 0
    audio.RecordTime = time.Now().Format(constants.DayTime)
    err=global.GVA_DB.Create(&audio).Error
    if err!=nil{
        global.GVA_LOG.Error(err.Error())
        return
    }
    return
}


func GetAllClass() (err error,res []model.BookAudio) {

    audios :=make([]model.BookAudio,0)

    err=global.GVA_DB.Table(model.BookAudio{}.TableName()).
        Group("class_name").Select("class_name").Find(&audios).Error

    if err!=nil{
        global.GVA_LOG.Error(err.Error())
        return nil,audios
    }
    return nil,audios

}



//
// GetAllBooks
// @Description: 查询书目录
// @param req
// @return err
// @return res
//
func GetAllBooks(req model.BookMenu) (err error,res []model.BookMenu) {

    audios :=make([]model.BookMenu,0)

    db:=global.GVA_DB.Table(model.BookMenu{}.TableName())
    if req.ClassName!=""{
        db = db.Where("class_name",req.ClassName)
    }
    err=db.Find(&audios).Error

    if err!=nil{
        global.GVA_LOG.Error(err.Error())
        return nil,audios
    }
    return nil,audios
}



func GetAudioByClass(req model.BookMenu) (err error,res []model.BookAudio){

    audios :=make([]model.BookAudio,0)

    db:=global.GVA_DB.Table(model.BookAudio{}.TableName()).
        Joins("left join book_menu m on m.id = book_audio.book_menu_id")

    if req.Id!=0{
        db = db.Where("book_audio.book_menu_id = ?",req.Id)
    }

    if req.ClassName!=""{
        db = db.Where("m.class_name = ?",req.ClassName)
    }
    if req.GroupName!=""{
       db = db.Where("m.group_name = ?",req.GroupName)
    }

    err=db.Select("book_audio.*").Find(&audios).Error

    if err!=nil{
        global.GVA_LOG.Error(err.Error())
        return nil,audios
    }
    return nil,audios






}
